//index.js
const wxaUserService = require('../../api/wxaUserService.js')
const bannerService = require('../../api/bannerService.js')
const memberService = require('../../api/memberService.js')
const couponService = require('../../api/couponService.js')
const storeService = require('../../api/storeService.js')
const auth = require('../../utils/auth.js')
const utils = require('../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    showModel: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    mobile: '',
    bindMobile: '',
    memberId: '',
    couponCount: 0, // 券数量
    storedValue: 0, // 储值余额
    score: 0, // 积分
    banners: [],
    encryptedData: "",
    iv: ''
  },
  onLoad: function () {
    /**
     * 先获取本地数据，查看是否有用户信息数据，
     * 如果有，直接那本地数据初始化界面，
     * 否则，提示用户手动授权登录，获取信息
     */
    try {
      var _userInfo = auth.getUser();
      if (_userInfo) {
        // Do something with return value
        this.setData({
          userInfo: _userInfo.wxaUser,
          hasUserInfo: true,
          mobile: _userInfo.member.mobile,
          memberId: _userInfo.member.id
        })
        if (this.data.memberId) {
          this.queryCoupon(1, 0, this.data.memberId);
          this.getMbrBalance();
          this.queryScore();
        }
      }
    } catch (e) {
      // Do something when catch error
    }
    // 获取banner
    this.getBanners();

    var self = this;
    // 定位，获取当前的经纬度信息
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        try {
          var tempAllStores = wx.getStorageSync('_allStores_'); // 获取缓存的所有门店
          if (tempAllStores) {
            // Do something with return value
            let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
            app.globalData.storeInfo = tempAllStores[tempIndex];
          } else {
            // 查询所有门店
            storeService.queryList().then(res => {
              var allStores = [];
              res.forEach(item => {
                if (item.status === 'OPEN') {
                  allStores.push(item)
                }
              });
              try {
                wx.setStorageSync('_allStores_', allStores)
              } catch (e) {
                console.log(e)
              }
              let tempIndex = self.getNearestStore(allStores, latitude, longitude);
              return allStores[tempIndex]
            }).then(res => {
              app.globalData.storeInfo = res;
            }).catch(err => {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            })
          }
        } catch (e) {
          // Do something when catch error
        }
      }
    })
  },
  getUserInfo: function (e) {
    wxaUserService.login().then(res => {
      app.globalData.userInfo = res;
      if (res.member) {
        auth.setUser(res)
        this.setData({
          userInfo: res.wxaUser,
          hasUserInfo: true,
          mobile: res.member.mobile,
          memberId: res.member.id
        })
      } else {
        // 弹出框，提示用户授权获取手机号
        this.setData({
          showModel: true
        })
      }
    }).then(() => {
      if (this.data.memberId) {
        this.queryCoupon(1, 0, this.data.memberId);
        this.getMbrBalance();
        this.queryScore();
      }
    }).catch(err => {
      console.log(err)
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = utils.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    return tempIndex;
  },

  /**
   * 获取banner图资源
   */
  getBanners: function () {
    bannerService.getBannerList('HOME').then(res => {
      this.setData({
        banners: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 查询用户相关的券
   * 调两个接口，一个内部券，一个外部券
   */
  queryCoupon: function (page, pageSize, memberId) {
    // 查询内部券，将查到的券相加
    couponService.queryCoupon(page, pageSize, memberId).then(res => {
      console.log(res)
      if (res.records && res.records.length > 0) {
        let count = 0;
        res.records.forEach(item => {
          if (item.status === 'OPEN')
            count++
        })
        if (this.data.couponCount) {
          count += this.data.couponCount;
        }
        this.setData({
          couponCount: count
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
    let couponData = {
      memberId: memberId
    }
    // 查询外部券
    couponService.queryExternalCoupons(couponData).then(res => {
      console.log(res)
      if (res && res.length > 0) {
        let count = 0;
        res.forEach(item => {
          if (item.status === 'OPEN')
            count++
        })
        if (this.data.couponCount) {
          count += this.data.couponCount;
        }
        this.setData({
          couponCount: count
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 查询储值余额
   */
  getMbrBalance: function () {
    memberService.getMbrBalance().then(res => {
      this.setData({
        storedValue: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 查询积分
   */
  queryScore: function () {
    memberService.getBalance(this.data.mobile).then(res => {
      console.log(res)
      this.setData({
        score: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 校验权限，判断是否登录，授权登录后才可以进入二级页面查看
   */
  checkAuthor: function () {
    if (this.data.hasUserInfo) {
      return true;
    } else {
      wx.showToast({
        title: "点击头像授权登录后才能查看哦~",
        icon: 'none',
        duration: 2000
      })
      return false
    }
  },
  // 跳转到储值充值中心
  toStoredValue: function () {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../balance/storedValue/storedValue'
      })
    }
  },
  // 跳转到我的优惠券
  toMyCoupon: function () {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../coupon/myCoupon/myCoupon'
      })
    }
  },
  // 跳转到领券中心
  toCouponCenter: function () {
    // wx.showToast({
    //   title: '该功能暂未开放，敬请期待',
    //   icon: 'none',
    //   duration: 2000
    // })
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../coupon/couponCenter/couponCenter',
      })
    }
  },
  // 跳转到我的积分
  toScore: function () {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../score/score',
      })
    }
  },
  // 跳转到我的会员卡
  toMyCard: function () {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../myCard/myCard',
      })
    }
  },
  // 跳转到我的礼品卡
  toGiftCard: function () {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../giftCard/giftCard/giftCard',
      })
    }
  },
  // 跳转到积分商城
  toScoreMall: function () {
    // wx.showToast({
    //   title: '该功能暂未开放，敬请期待',
    //   icon: 'none',
    //   duration: 2000
    // })
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../scoreMall/scoreMall/scoreMall',
      })
    }
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    this.setData({
      userInfo: {},
      mobile: '',
      couponCount: 0,
      storedValue: 0,
      score: 0,
      hasUserInfo: false
    })
    this.onLoad();
    wx.stopPullDownRefresh();
  },

  /**
   * 弹出框取消按钮操作
   */
  handelCancel: function (e) {
    this.setData({
      showModel: false
    })
  },
  /**
   * 获取用户的手机号
   */
  getPhoneNumber: function (e) {
    if (!this.data.bindMobile) {
      // 执行解析手机号信息操作
      wxaUserService.parseWxaMobile(e.detail.encryptedData, e.detail.iv).then(res => {
        console.log(res)
        this.setData({
          bindMobile: res,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        })
      }).catch(err => {
        wx.showToast({
          title: "未知错误，即将跳转到手动绑定手机号",
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateTo({
            url: '../bindMobile/bindMobile',
          })
        }, 2000)
      })
    }
  },
  /**
   * 处理通过微信授权拿到手机号，然后绑定操作
   */
  handelBindMobile: function () {
    var self = this;
    // 执行绑定手机号,绑定成功后显示用户头像和昵称
    wxaUserService.bindMobileByEncrypt(this.data.encryptedData, this.data.iv).then(res => {
      console.log(res)
      self.setData({
        mobile: res.mobile,
        showModel: false
      })
    }).then(res => {
      self.getUserInfo();
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 去手动绑定手机号
   */
  toBindMobile: function () {
    wx.navigateTo({
      url: '../bindMobile/bindMobile',
    })
  },

  /**
   * banner图点击事件，会员小程序只支持跳转到小程序有的模块中
   * 未授权登录，不进行跳转
   */
  handelBannerClick: function (e) {
    let clickItem = ''
    this.data.banners.forEach(item => {
      if (item.id === e.currentTarget.dataset.id) {
        console.log(item)
        clickItem = item;
      }
    })
    // 授权登录后才能根据banner 的跳转类型进行跳转
    if (this.checkAuthor()) {
      // 只跳转应用内模块，不跳转链接，商品等
      if (clickItem.linkType === 'APP') {
        if (clickItem.appReturnType === 'MEMBER_CARD') {
          // 如果跳转类型是会员卡，跳转到会员码页面
          wx.navigateTo({
            url: '../myCard/myCard',
          })
        } else if (clickItem.appReturnType === 'RECHARGE') {
          // 如果跳转类型是充值，跳转到储值充值界面
          wx.navigateTo({
            url: '../balance/storedValue/storedValue',
          })
        } else if (clickItem.appReturnType === 'GIFTCARD') {
          // 如果跳转类型是礼品卡，跳转到礼品卡界面
          wx.navigateTo({
            url: '../giftCard/giftCard/giftCard',
          })
        }
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})